<template>
  <el-dialog
      v-model="dialogVisible"
      title="修改客户"
      width="700px"
      :before-close="handleCloseDialog"
  >
    <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="120px"
        class="customer-edit-form"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="客户名" prop="name">
            <el-input
                v-model="editForm.name"
                placeholder="请输入公司名/客户名"
                class="customer-edit-form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contact">
            <el-input
                v-model="editForm.contact"
                placeholder="请输入联系人"
                class="customer-edit-form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input
                v-model="editForm.phone"
                placeholder="请输入联系电话"
                class="customer-edit-form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input
                v-model="editForm.email"
                placeholder="请输入电子邮箱"
                class="customer-edit-form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="地址" prop="address">
        <el-input
            v-model="editForm.address"
            placeholder="请输入地址"
            class="customer-edit-form-input"
            type="textarea"
            :rows="2"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="customer-edit-dialog-footer">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {getCustomer, updateCustomer} from "../../../api/customerApi.js";

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  customerId: {
    type: Number,
    default: null
  }
})

// 定义emits
const emits = defineEmits(['update:visible', 'success'])

// 对话框显示状态
const dialogVisible = ref(false)

// 表单引用
const editFormRef = ref()

// 修改表单数据
const editForm = reactive({
  id: null,
  name: '',
  contact: '',
  phone: '',
  email: '',
  address: ''
})

// 表单验证规则
const editFormRules = reactive({
  name: [
    {required: true, message: '请输入客户名', trigger: 'blur'},
    {min: 1, max: 100, message: '客户名长度在 1 到 100 个字符', trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '请输入有效的电子邮箱地址', trigger: ['blur', 'change']}
  ]
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal && props.customerId) {
    loadCustomerData()
  }
})

// 监听dialogVisible变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emits('update:visible', false)
  }
})

// 加载客户数据
const loadCustomerData = async () => {
  if (!props.customerId) return;
  try {
    const data = await getCustomer(props.customerId);
    initFormData(data);
  } catch (error) {
    console.error('获取客户详情失败:', error);
    ElMessage.error('获取客户详情失败');
  }
}

// 初始化表单数据
const initFormData = (data) => {
  if (data) {
    editForm.id = data.id
    editForm.name = data.name || ''
    editForm.contact = data.contact || ''
    editForm.phone = data.phone || ''
    editForm.email = data.email || ''
    editForm.address = data.address || ''
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  editForm.id = null
  editForm.name = ''
  editForm.contact = ''
  editForm.phone = ''
  editForm.email = ''
  editForm.address = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    await updateCustomer(editForm)
    emits('success')
    handleCloseDialog()
  } catch (error) {
    console.error('表单验证或提交失败:', error)
    ElMessage.error('修改客户失败')
  }
}
</script>

<style scoped lang="scss">
.customer-edit {
  &-form {
    padding: 16px 0;

    &-input {
      width: 100%;
    }
  }

  &-dialog {
    &-footer {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
    }
  }
}
</style>

